package com.lagou.controller;

import com.lagou.domain.FileSystem;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author : liuchangling
 * @Descrition :
 * @Date： Created in 1:20 下午 2021/8/18
 */
@Controller
public class UploadMovies {
    //模拟加锁的常量
    private static final String UPLOAD_LOCK = "upload_lock";

    @Autowired
    private Redisson redisson;

    @Bean
    public Redisson redisson() {
        Config config = new Config();
        // 使用单个redis服务器
        config.useSingleServer().setAddress("redis://192.168.174.128:6379").setDatabase(0);
        return (Redisson) Redisson.create(config);
    }

    @RequestMapping("uploadMovies")
    @ResponseBody
    public List<FileSystem> uploadMovies(Model model, MultipartHttpServletRequest request) throws Exception {
        List<FileSystem> list=new ArrayList<>();
        FileSystem fileSystem = new FileSystem();
        //获取上传的内容，因为有多条，所以使用map
        MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
        //获取map中fname对应的数据信息
        List<MultipartFile> files = multiFileMap.get("fname");
        //遍历加锁上传、解锁
        for(int i=0;i<files.size();i++) {
            MultipartFile file=files.get(i);
            //当获取的名称不为空时，获取锁
            if (file != null) {
                RLock rLock = redisson.getLock(UPLOAD_LOCK);
                rLock.lock(60, TimeUnit.SECONDS);
                try {
                    fileSystem = uploadToDfs(file);
                    list.add(fileSystem);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    rLock.unlock();
                }
            }
        }
        return list;
    }

    //上传数据
    public FileSystem uploadToDfs(MultipartFile file) throws Exception {
        FileSystem fileSystem1 = new FileSystem();
        String oldFileName = file.getOriginalFilename();
        // 通过字符串截取的方式，从文件原始名中获取文件的后缀 1.jpg
        String hou = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
        // 为了避免文件因为同名而覆盖，生成全新的文件名
        String newFileName = UUID.randomUUID().toString() + "." + hou;
        // 创建web服务器保存文件的目录(预先创建好D:/upload目录，否则系统找不到路径，会抛异 常)
        File toSaveFile = new File("E:/upload/" + newFileName);
        // 将路径转换成文件
        file.transferTo(toSaveFile);
        // 获取服务器的绝对路径
        String newFilePath = toSaveFile.getAbsolutePath();
        /* 2、把文件从web服务器上传到FastDFS*/
        ClientGlobal.initByProperties("config/fastdfs-client.properties");
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageServer storageServer = null;
        StorageClient1 client = new StorageClient1(trackerServer, storageServer);
        NameValuePair[] list = new NameValuePair[1];
        list[0] = new NameValuePair("fileName", oldFileName);
        String fileId = client.upload_file1(newFilePath, hou, list);
        trackerServer.close();
        // 封装fileSystem数据对象
        fileSystem1.setFileId(fileId);
        fileSystem1.setFileName(oldFileName);
        fileSystem1.setFilePath(fileId);
        //已经上传到FastDFS上，通过fileId来访问图 片，所以fileId即为文件路径
        return fileSystem1;
    }

}
